package physical;

import domain.Account;
import domain.Balance;
import domain.Card;
import domain.Customer;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class CardReader {

	private Account account;
	
	public CardReader(){
		this.account = new Account();
	}
	
	public 	Account readCard(String cardNumber){
		File file = new File("customer.txt");
		if(!file.exists()){
		    System.out.println("Source file does not exist");
		    try(PrintWriter output = new PrintWriter(file);){
		        output.println("6228210089201003878,441625199705135719,\u5f20\u5fd7\u4f1f,13416145491,10000,888888");
				output.println("123,441625199705135719,\u5f20\u5fd7\u4f1f,13416145491,50000,000000");
            } catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
        Map<String,String[]> customerList = new HashMap();
        try(Scanner input = new Scanner(file).useDelimiter(",");){
		    while(input.hasNext()){
                String[] line = input.nextLine().split(",");
                customerList.put(line[0],line);
            }
        } catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		String[] arr = customerList.get(cardNumber);
		if(arr != null){
			this.account.setCard(new Card(cardNumber));
			this.account.setCustomer(new Customer(arr[1], arr[2], arr[3]));
			this.account.setBalance(new Balance(arr[4]));
			this.account.setPassword(arr[5]);
			return account;
		}else return null;
	}
	
	public boolean verifyPassword(String password){
		return this.account.getPassword().equals(password);
	}
	
	public Account refundCard(){
		this.account = new Account();
		return account;
	}

	public Account getAccount() {
		return account;
	}
	
}
